import cv2
import numpy as np

#tpl0 = cv2.imread("3920_tpl.jpg")
#target0 = cv2.imread("1_test.jpg")
#tpl =  cv2.cvtColor(tpl0, cv2.COLOR_BGR2GRAY)
#target = cv2.cvtColor(target0, cv2.COLOR_BGR2GRAY)

# tpl0 = cv2.imread("3920_tpl.jpg")
# tpl =  cv2.cvtColor(tpl0, cv2.COLOR_BGR2GRAY)
# cv2.imwrite('3920_tpl_binary.jpg',tpl)


#tpl = cv2.imread("1_test_tp_binary.jpg",-1)
tpl = cv2.imread("3920_tpl_binary.jpg",-1)
target = cv2.imread("3920_1.jpg",-1)
target = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)
methods = [cv2.TM_SQDIFF,cv2.TM_CCORR_NORMED,cv2.TM_CCOEFF_NORMED]
th,tw = tpl.shape

for md in methods:
    print(md)
    result = cv2.matchTemplate(target, tpl, md)
    min_val,max_val,min_loc,max_loc = cv2.minMaxLoc(result)
    print(min_loc,max_loc)
    if md == cv2.TM_SQDIFF:
        tl = min_loc
    else:
        tl = max_loc
    print(tl)
    br = (tl[1]+th,tl[0]+tw)
    print(br)
    #cv2.rectangle(target,tl,br,(0,0,255),2)
    #cv2.namedWindow("match-"+np.str(md),cv2.WINDOW_NORMAL)
    #cv2.imshow("match-"+np.str(md),target)
#cv2.waitKey(0)
#cv2.destroyAllWindows()

print("finish!")